package com.will.netty.eventLoop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * @author Will
 * @description:
 *              1. 演示 NioEventLoop 处理 IO 事件
 *              2. handler 执行中如何换人
 * @date 2023-05-25 22:46
 * @version: 1.0
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        DefaultEventLoopGroup normalGroup = new DefaultEventLoopGroup(2);

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);

        new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel channel) throws Exception {
                                log.debug("init...");
                                ChannelPipeline pipeline = channel.pipeline();
                                pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                                pipeline.addLast(normalGroup, "myhandler", new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = (ByteBuf) msg;
                                        log.debug(buf.toString(Charset.defaultCharset()));
                                        ctx.fireChannelRead(msg); // 让消息传递给下一个handler
                                    }
                                });
                                pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = (ByteBuf) msg;
                                        log.debug(buf.toString(Charset.defaultCharset()));
                                    }
                                });
                            }
                        })
                .bind(8080);
    }
}
